package com.qiangou.controller;

import java.io.IOException;
import java.io.OutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.entity.Login_Log;
import com.entity.User;
import com.qiangou.service.LoginLogService;
import com.qiangou.service.UserService;
import com.util.DateUtil;
import com.util.SecurityCode;
import com.util.SecurityImage;

@Controller("loginController")
public class LoginController {
	@Resource(name="userService")
	private UserService userService;
	@Resource(name="loginLogService")
	private LoginLogService loginLogService;
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public @ResponseBody String login(Model model,String username,String password,String verifyCode,HttpSession session,HttpServletRequest request) {
		String cc = (String)session.getAttribute("cc");
		User user=userService.login(username, password);
		if(cc==null){
			return "3";
		}
		if(!cc.equals(verifyCode)) {
			return "2";//验证码错误
		}
		if(user!=null){
			
			Login_Log ll=new Login_Log();
			ll.setUserid(user.getId());
			ll.setUsername(username);
			ll.setTime(DateUtil.getStringDate());
			ll.setIp(request.getRemoteHost());
			loginLogService.saveLog(ll);//记录登入信息set
			session.setAttribute("username",user.getUsername());
			session.setAttribute("userid",user.getId());
			return "0";//登入成功
		}else{
			return "1";//账号或密码错误
		}
	} 
	@RequestMapping(value="/logout",method=RequestMethod.POST)
	public String logout(HttpSession session) {
		session.removeAttribute("username");
		session.removeAttribute("userid");
		return "index";
	}
	@RequestMapping(value="/checkLogin",method=RequestMethod.POST)
	public @ResponseBody String checkSession(HttpSession session) {
		String UserName=String.valueOf(session.getAttribute("username"));
		if(UserName!=null&&!"".equals(UserName)&&!"null".equals(UserName)){
			return "ok";
		}
		return "no";
	} 
	@RequestMapping("/drawCheckCode")
	public void drawCheckCode(HttpServletResponse resp, HttpSession session)
			throws IOException {
		String checkcode = SecurityCode.getSecurityCode();
		session.setAttribute("cc", checkcode);
		OutputStream os = resp.getOutputStream();
		ImageIO.write(SecurityImage.createImage(checkcode), "jpg", os);
	}
	
}
